class AppDiscovery

  #启动守护线程
  def AppDiscovery.start_discovery_thread
    Thread.new {
      while(true)
        begin
          DaemonLogger.logger.info('开始加载 yazuo_apps ...')
          Timeout::timeout(60) do
            AppDiscovery.discover
            AppDiscovery.discover_apps_of_huidu
          end
          DaemonLogger.logger.info('完成加载 yazuo_apps ...')
        rescue => e
          DaemonLogger.logger.error "AppsLoader.flush_apps 执行失败: #{e.message}"
          DaemonLogger.logger.error e.backtrace.join("\n")
        ensure
          ActiveRecord::Base.connection_pool.release_connection
        end
        sleep(60)
      end
    }
  end

  #定时执行该方法，监测新增的app，更新到数据库
  def AppDiscovery.discover
    #登录上线前部署机，获取app列表
    app_list = DeployToolUtil.get_app_list_from_cap(DeployToolUtil.env_production)

    #从库里查询到以保存的app
    apps = App.all
    app_names_saved = apps.collect { |app| app.name }
    app_names_tmp = Dir.glob('/deploy/*').select { |f| File.directory? f }.collect { |f| File.basename(f) }
    DaemonLogger.logger.debug app_names_tmp

    #比较二者，得出新增app，入库
    app_names_new = app_list - app_names_saved
    app_names_new.each { |app_name|
      DaemonLogger.logger.info('new app %s' % app_name)
      @app = App.new()
      @app.name = app_name
      @app.save()
    }

  end

  #定时执行该方法，监测灰度环境的app，更新到内存
  def AppDiscovery.discover_apps_of_huidu
    #登录上线前部署机，获取app列表
    app_list = DeployToolUtil.get_app_list_from_cap(DeployToolUtil.env_huidu)
    #写入变量
    DeployToolUtil.apps_of_huidu = app_list
  end
end